<?php
namespace Admin\Controller;

class Controller extends \Think\Controller {
    protected $indexExpr = array(); //index方法关联的条件表达式
    protected $sortExpr  = '';      //排序表达式

    public function index() {
        $m    = D2();
        $page = $m->where($this->indexExpr)->order($this->sortExpr)->page2();

        $this->assign('page', $page)
             ->display();
    }

    /**
     * _before_index 
     * 组装index方法的查询参数
     * 
     * @access public
     * @return void
     */
    public function _before_index() {
        $m          = D(CONTROLLER_NAME);
        $searchJson = '';
        $expr       = array();

        if (method_exists($m, 'buildSearchExpr')) {
            if($search = $m->buildSearchExpr($_GET)) {
                $searchJson = $search['json'];
                $expr       = $search['expr'];
                $sortExpr   = $search['sort'];
            }
        }

        if(!empty($searchJson)) {
            $this->assign('searchJson', $searchJson);
        }

        $this->indexExpr = $expr;
        $this->sortExpr  = $sortExpr;
    }

    public function del() {
        $id = I('request.id');

        if (empty($id)) {
            showJson(['status' => false, 'msg' => '参数不完整，无法删除数据']);
        }

        $m = D2();

        try {
            $r = $m->del($id) 
                 ? ['status' => true,  'msg' => '删除成功']
                 : ['status' => false, 'msg' => '删除出错'];
        } catch(\Exception $e) {
            $r = ['satus' => false, 'msg' => $e->getMessage()];
        }

        showJson($r);
    }

    public function modify() {
        $id = I('get.id', 0, 'intval');

        if (empty($id)) {
            throw new \Exception("参数不完整，无法获取数据");  
        }

        $m    = D2();
        $expr = ['id' => $id];

        if (!$record = $m->where($expr)->find()) {
            throw new \Exception("未找到相关数据");
        }

        $this->assign('record', $record)
             ->display();
    }

    public function doSave() {
        $d = $_POST;
        $m = D2();

        try {
            $r = $m->save2($d)
                 ? ['status' => true,  'msg' => '保存成功']
                 : ['status' => false, 'msg' => '保存出错'];
        } catch(\Exception $e) {
            $r = ['status' => false, 'msg' => $e->getMessage()];
        }

        showJson($r);
    }


}
